package com.bs.resa.web;

import com.bs.resa.common.RedisUtils;
import com.bs.resa.pojo.AdminUser;
import com.bs.resa.service.AdminUserService;
import com.bs.resa.service.TaskService;
import com.bs.resa.shiro.ShiroUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @Author lin
 * @date 2019/3/8 13:26
 */
@Controller
public class LoginController {
    private static Logger logger= LoggerFactory.getLogger(LoginController.class);
    protected Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    @Value("${fastdfs_setting.IMAGE_SERVER_URL}")
    private String url;

    @Autowired
    AdminUserService adminUserService;
    @Autowired
    TaskService taskService;
    @Autowired
    RedisUtils redisUtils;

    @ApiOperation(value = "进入登录页面",notes = "GET")
    @RequestMapping(value = "/login" ,method = RequestMethod.GET)
    public ModelAndView login(ModelAndView model){
        logger.info("进入登录页面");
        model.addObject("message","Welcome");
        model.setViewName("login");
        return model;
    }

    @ApiOperation(value = "进入主页",notes = "GET")
    @RequestMapping(value = "html/content.do" ,method = RequestMethod.GET)
    public ModelAndView homes(ModelAndView model){
        Map<String,Object> map=taskService.queryMytaskCount();
        System.out.println("主页数据0");
        System.out.println(map);
        model.setViewName("html/content");
        model.addObject("map",map);
        return model;
    }

    @ApiOperation(value = "登录提交",notes = "POST")
    @ResponseBody
    @RequestMapping(value = "/submitLogin.do" ,method = RequestMethod.POST)
    public Object loginSubmit(HttpServletRequest request,String username, String password){
        logger.info("登录提交");
        logger.info("[username:"+username+",password:"+password+"]");
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,ShiroUtils.getStrByMD5(password));
            try {
                subject.login(token);
                resultMap.put("code", "200");
                resultMap.put("message", "success");

            }catch (DisabledAccountException dax) {
                logger.info("用户名为:" + username + " 用户已经被禁用！");
                resultMap.put("status", 500);
                resultMap.put("message", "帐号已被禁用！");
            } catch (ExcessiveAttemptsException eae) {
                logger.info("用户名为:" + username + " 用户登录次数过多，有暴力破解的嫌疑！");
                resultMap.put("status", 500);
                resultMap.put("message", "Too many logins");
            } catch (AccountException ae) {
                logger.info("用户名为:" + token.getPrincipal() + " 帐号或密码错误！");
                resultMap.put("code","500");
                resultMap.put("message","username or password error");
            } catch (AuthenticationException ae) {
                logger.info("------------------身份认证失败-------------------");
                resultMap.put("status", 500);
                resultMap.put("message", "Authentication failed");
            }
            catch (Exception e){
                System.out.println("异常");
                resultMap.put("code","500");
                resultMap.put("message",e.getMessage());
            }
//        }else{
//            resultMap.put("code","500");
//            resultMap.put("message","username or password error");
////            model.setViewName("login");
//        }
        return resultMap;
    }


    /**
     * @Description: 退出
     */
    @ApiOperation(value = "退出",notes = "GET")
    @RequestMapping(value="logout.do",method=RequestMethod.GET)
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
            redisUtils.delObject("userinfo");
        } catch (Exception e) {
            logger.error("errorMessage:" + e.getMessage());
        }
        return "redirect:login";
    }

    /**
     * @Description: 主页
     */
    @ApiOperation(value = "跳转到主页",notes = "GET")
    @RequestMapping(value="/home.do",method=RequestMethod.GET)
    @ResponseBody
    public ModelAndView home(ModelAndView model){
        AdminUser adminUser= (AdminUser) redisUtils.getObject("userinfo");
//        if(adminUser==null){
//            model.addObject("message","Please log in again");
//            model.setViewName("login");
//        }else{
            resultMap.put("url",url);
            resultMap.put("adminuser",adminUser);
            model.addObject("message",resultMap);
            model.setViewName("home");
//        }


        return model;
    }

}
